package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.*;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.entity.ApAuthor;
import com.heima.article.entity.ApCollection;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.feign.UserFeign;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.service.IApAuthorService;
import com.heima.article.service.IApCollectionService;
import com.heima.article.vo.HotArticleVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppUserThreadLocal;
import org.apache.kafka.common.protocol.types.Field;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2021-05-25
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Autowired
    private IApCollectionService iApCollectionService;

    @Autowired
    private IApArticleContentService apArticleContentService;

    @Autowired
    private IApAuthorService iApAuthorService;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult<Long> saveOrUpdateArticle(ArticleDto dto) {
        //判断有没有Id
        if (dto.getId() == null) {
            //保存文章
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto, apArticle);
            this.save(apArticle);
            //保存文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentService.save(apArticleContent);
            return ResponseResult.okResult(apArticle.getId());
        }
        //有Id修改文章
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        this.updateById(apArticle);
        //修改文章内容
        LambdaUpdateWrapper<ApArticleContent> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ApArticleContent::getArticleId, dto.getId());
        updateWrapper.set(ApArticleContent::getContent, dto.getContent());
        apArticleContentService.update(updateWrapper);
        return ResponseResult.okResult(apArticle.getId());
    }

    @Override
    public ResponseResult load(ArticleHomeDto dto, int type) {
        //设置分页
        //判断条件
        //刷新的话，比最小时间还小
        //加载更多，比最大时间更大
        //过滤下架
        if (dto.getSize() == null || dto.getSize() <= 0 || dto.getSize() >= 50) {
            dto.setSize(10);
        }
        //设置分页
        IPage<ApArticle> page = new Page<>(1, dto.getSize());
        LambdaUpdateWrapper<ApArticle> query = new LambdaUpdateWrapper<>();
        if (dto.getChannelId() != null && dto.getChannelId() != 0) {
            //判断条件
            query.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        query.orderByDesc(ApArticle::getPublishTime);
        query.eq(ApArticle::getIsDelete, false);
        query.eq(ApArticle::getIsDown, false);
        //刷新的话，比最小时间还小
        if (type == 0) {
            query.gt(ApArticle::getPublishTime, dto.getMaxTime());
        }

        //加载更多，比最大时间更大
        if (type == 1) {
            query.lt(ApArticle::getPublishTime, dto.getMinTime());
        }

        IPage<ApArticle> iPage = this.page(page, query);
        List<ApArticle> records = iPage.getRecords();
        return ResponseResult.okResult(records);
    }

    @Override
    public ResponseResult load2(ArticleHomeDto dto, Integer type, boolean firstPage) {
        //判断是否是首页查询，如果是，从redis里查询
        if (firstPage){
            int channelId = 0;
            if (dto.getChannelId() != null){
                channelId = dto.getChannelId();
            }
            String redisKey = "hot_article_HotArticle"+channelId;
            String json = redisTemplate.opsForValue().get(redisKey);
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(json,HotArticleVo.class);
            return ResponseResult.okResult(hotArticleVoList);
        }
        //否则从数据库查询
        return load(dto,type);
    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //查询
        ApArticle apArticle = this.getById(dto.getArticleId());
        if (apArticle==null || apArticle.getIsDown() || apArticle.getIsDelete()){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //根据ID查文章内容
        LambdaUpdateWrapper<ApArticleContent> query = new LambdaUpdateWrapper<>();
        query.eq(ApArticleContent::getArticleId,dto.getArticleId());
        ApArticleContent apArticleContent = apArticleContentService.getOne(query);

        Map<String,Object> map = new HashMap<>();
        map.put("config",apArticle);
        map.put("content",apArticleContent);
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        //构建Entry对象
        EntryDto entryDto = new EntryDto();
        //查询用户是否登录
        User user = AppUserThreadLocal.get();
        if (user != null) {
            entryDto.setUserId(user.getUserId());
        }
        entryDto.setEquipmentId(dto.getEquipmentId());

        ResponseResult<ApBehaviorEntry> responseResult = behaviorFeign.getEntry(entryDto);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApBehaviorEntry entry = responseResult.getData();
            if (entry!=null){
                if (dto.getOperation()==0){
                    LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
                    query.eq(ApCollection::getEntryId, entry.getId());
                    query.eq(ApCollection::getArticleId, dto.getArticleId());
                    ApCollection collection = iApCollectionService.getOne(query);
                    if (collection== null){
                        ApCollection apCollection = new ApCollection();
                        apCollection.setEntryId(entry.getId());
                        apCollection.setArticleId(dto.getArticleId());
                        apCollection.setCollectionTime(new Date());
                        iApCollectionService.save(apCollection);
                    }
                } else {
                    LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
                    query.eq(ApCollection::getEntryId,entry.getId());
                    query.eq(ApCollection::getArticleId,dto.getArticleId());
                    iApCollectionService.remove(query);
                }
            }
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult loadBehavior(ArticleInfoDto dto) {
        Boolean isfollow = false;
        Boolean islike = false;
        Boolean isunlike = false;
        Boolean iscollection = false;

        User user = AppUserThreadLocal.get();
        if (user != null) {
            FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
            followBehaviorDto.setUserId(user.getUserId());
            ApAuthor apAuthor = iApAuthorService.getById(dto.getAuthorId());
            followBehaviorDto.setFollowId(apAuthor.getUserId());
            ResponseResult<ApUserFollow> userFollowResponseResult = userFeign.getFollow(followBehaviorDto);
            if (userFollowResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
                ApUserFollow apUserFollow = userFollowResponseResult.getData();
                if (apUserFollow != null) {
                    isfollow = true;
                }
            }
        }

        // 查询用户的点赞记录
        LikesBehaviorDto likesBehaviorDto = new LikesBehaviorDto();
        likesBehaviorDto.setArticleId(dto.getArticleId());
        if (user != null) {
            likesBehaviorDto.setUserId(user.getUserId());
        }
        likesBehaviorDto.setEquipmentId(dto.getEquipmentId());
        ResponseResult<ApLikesBehavior> likesBehaviorResponseResult = behaviorFeign.getLike(likesBehaviorDto);
        if (likesBehaviorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApLikesBehavior apLikesBehavior = likesBehaviorResponseResult.getData();
            if (apLikesBehavior != null && apLikesBehavior.getOperation() == 0) {
                islike = true;
            }
        }
        // 查询用户的不喜欢记录
        UnLikesBehaviorDto unLikesBehaviorDto = new UnLikesBehaviorDto();
        unLikesBehaviorDto.setArticleId(dto.getArticleId());
        unLikesBehaviorDto.setEquipmentId(dto.getEquipmentId());
        if (user != null) {
            unLikesBehaviorDto.setUserId(user.getUserId());
        }
        ResponseResult<ApUnlikesBehavior> unlikesBehaviorResponseResult = behaviorFeign.getUnlikes(unLikesBehaviorDto);
        if (unlikesBehaviorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApUnlikesBehavior apUnlikesBehavior = unlikesBehaviorResponseResult.getData();
            if (apUnlikesBehavior != null && apUnlikesBehavior.getType() == 0) {
                isunlike = true;
            }
        }
        // 查询用户的收藏记录
        LambdaQueryWrapper<ApCollection> queryWrapper = new LambdaQueryWrapper<>();
        EntryDto entryDto = new EntryDto();
        entryDto.setEquipmentId(dto.getEquipmentId());
        if (user != null) {
            entryDto.setUserId(user.getUserId());
        }
        ResponseResult<ApBehaviorEntry> entryResponseResult = behaviorFeign.getEntry(entryDto);
        if (entryResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApBehaviorEntry behaviorEntry = entryResponseResult.getData();
            queryWrapper.eq(ApCollection::getEntryId, behaviorEntry.getId());
            queryWrapper.eq(ApCollection::getArticleId, dto.getArticleId());
            ApCollection apCollection = iApCollectionService.getOne(queryWrapper);
            if (apCollection != null) {
                iscollection = true;
            }
        }

        Map<String,Boolean> map = new HashMap<>();
        map.put("isfollow",isfollow);
        map.put("islike",islike);
        map.put("isunlike",isunlike);
        map.put("iscollection",iscollection);
        return ResponseResult.okResult(map);
    }
}
